﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace SlamCms.Configuration
{
	public abstract class Configuration
	{
		private XDocument _configurationXml;
		protected XDocument ConfigurationXml
		{
			get
			{
				if (_configurationXml == null)
				{
					throw new NullReferenceException("Configuration XML must be loaded prior to referencing ConfigurationXml.");
				}
				return _configurationXml;
			}
		}

		private Dictionary<string, List<ConfigurationElement>> _elements;
		public List<ConfigurationElement> this[string elementName]
		{
			get
			{
				List<ConfigurationElement> returnElements = null;
				if (_elements.ContainsKey(elementName))
				{
					returnElements = _elements[elementName];
				}
				else
				{
					returnElements = new List<ConfigurationElement>();
				}
				return returnElements;
			}
		}

		public Configuration()
		{
			_elements = new Dictionary<string, List<ConfigurationElement>>();
		}

		public bool ContainsElement(string elementName)
		{
			return _elements.ContainsKey(elementName);
		}

		protected virtual void Load(XDocument configurationXml)
		{
			_configurationXml = configurationXml;

			foreach (XElement element in configurationXml.Root.Elements())
			{
				AddElement(element, "");
			}
		}

		private void AddElement(XElement element, string prependName)
		{
			if (_elements.ContainsKey(prependName + element.Name))
			{
				_elements[prependName + element.Name].Add(new ConfigurationElement(element));
			}
			else
			{
				var newElementList = new List<ConfigurationElement>();
				newElementList.Add(new ConfigurationElement(element));
				_elements.Add(prependName + element.Name, newElementList);
			}

			foreach (XElement childElement in element.Elements())
			{
				AddElement(childElement, prependName + element.Name + ".");
			}
		}
	}
}
